package com.example.javaeekeshe.controller;

import com.example.javaeekeshe.pojo.AccountBean;
import com.example.javaeekeshe.pojo.AddressBean;
import com.example.javaeekeshe.service.IAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/account")
public class MyController {
    @Autowired
    IAddressService addressService;


    @RequestMapping("/myinfo")
    public String toMyInfo(){
        return "/user/myinfo";
    }

    /**
     * 注销
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.setAttribute("loginUser",null);
        return "redirect:/index";
    }

    /**
     * 我的
     * @return
     */
    @RequestMapping("/my")
    public String my(){
        return "/user/my";
    }

    /**
     * 地址管理页
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/toaddress")
    public String toAddress(Model model, HttpSession session){
        AccountBean loginUser = (AccountBean) session.getAttribute("loginUser");
        List<AddressBean> addresses = addressService.selectByUId(loginUser.getId());
        model.addAttribute("addresses",addresses);
        return "/user/address/index";
    }

    /**
     * 删除地址
     * @param id
     * @return
     */
    @RequestMapping("/del/{id}")
    public String del(@PathVariable("id") Integer id){
        addressService.delAddressByid(id);
        return "redirect:/account/toaddress";
    }

    /**
     * 转向添加页
     * @param session
     * @return
     */
    @RequestMapping("/toadd")
    public String toadd(HttpSession session){
        return "/user/address/add";
    }

    @RequestMapping("/addAddress")
    public String add(AddressBean address,String longAddress,HttpSession session){
        AccountBean loginUser = (AccountBean) session.getAttribute("loginUser");
        address.setUid(loginUser.getId());
        address.setAddress(address.getAddress()+longAddress);
        addressService.addAddress(address);
        return "redirect:/account/toaddress";
    }

    @RequestMapping("/edit/{id}")
    public String toEdit(@PathVariable("id") Integer id,Model model){
        AddressBean address = addressService.selectAddressByid(id);
        model.addAttribute("address",address);
        return "/user/address/edit";
    }


    @RequestMapping("/update")
    public String update(AddressBean address){
        addressService.update(address);
        return "redirect:/account/toaddress";
    }


}
